#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/4/16 14:29
# @Author    :cjw
from common.page import Page
from setting.setting import SCHOOL_URL, YAML_ELEMENT
from util.file_reader import YmlReader
from util.baidu_ai_code import get_image_code


class LoginPage(Page):
    url = SCHOOL_URL
    locators = YmlReader(YAML_ELEMENT['lp']).data

    def get(self):
        """打开网页"""
        self.driver.get(self.url)

    def login(self, username: str = 'xxx', password: str = 'xxx'):
        """登录"""
        # 首先识别获取图片验证码
        verify_img_el = self.img
        verify_code = get_image_code(verify_img_el.screenshot_as_png)

        self.username.send_keys(username)
        self.password.send_keys(password)
        self.pic_code.send_keys(verify_code)
        self.log_btn.click()

        # 验证码验证错误，重新登录
        try:
            if self.element(self.locators['error_msg'], 1) or \
                    self.element(self.locators['code_msg']):
                self.get()
                self.login(username, password)
        except Exception:
            pass


if __name__ == '__main__':
    obj = LoginPage()
    obj.get()
    obj.login()
    obj.driver.quit()
